<?php

require_once dirname ( __FILE__ ) . '/../lib/materialGeneratorConfiguration.class.php';
require_once dirname ( __FILE__ ) . '/../lib/materialGeneratorHelper.class.php';

/**
 * material actions.
 *
 * @package    sf_portal
 * @subpackage material
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class materialActions extends autoMaterialActions {
	
protected function executeBatchPub(sfWebRequest $request)
  {
    $ids = $request->getParameter('ids');

    $count = 0;
    foreach (MaterialPeer::retrieveByPks($ids) as $object)
    {
      $object->setPub(true);
      
      if ($object->save())
      {
        $count++;
      }
    }

    if ($count >= count($ids))
    {
      $this->getUser()->setFlash('notice', 'Изменения внесены');
    }
    else
    {
      $this->getUser()->setFlash('error', 'Ошибка');
    }

    $this->redirect('@material');
  }
	
	public function executeIndex(sfWebRequest $request) {
		
		
		 
		///Зоздаем Корневой если его нет
		/*
	    $c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, $this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ) );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Мои каталоги');
			$root->makeRoot ();
			$root->setScopeIdValue ( $this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ) ); 
			$root->save ();
		}
		
	*/
		
	    /////Новости
	    /*
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 19 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Зарубежье');
			$root->makeRoot ();
			$root->setScopeIdValue ( 19 ); 
			$root->save ();
		}
*/
		//////
		
	   
		
        /////Подарки
        /*
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 16 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Подарки');
			$root->makeRoot ();
			$root->setScopeIdValue ( 16 ); 
			$root->save ();
		}
   */
		//////
	/*	
	    /////Типы товаров
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 2 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Типы товаров');
			$root->makeRoot ();
			$root->setScopeIdValue ( 2 ); 
			$root->save ();
		}
		//////
		
		/////Виды деятельности
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 3 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Виды деятельности');
			$root->makeRoot ();
			$root->setScopeIdValue ( 3 ); 
			$root->save ();
		}
		//////
		
		
		/////Производители
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 4 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Производители');
			$root->makeRoot ();
			$root->setScopeIdValue ( 4 ); 
			$root->save ();
		}
		//////
		
		/////Регионы
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 5 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Регионы');
			$root->makeRoot ();
			$root->setScopeIdValue ( 5 ); 
			$root->save ();
		}
		//////
		
		/////Публикации
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 6 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Регионы');
			$root->makeRoot ();
			$root->setScopeIdValue ( 6 ); 
			$root->save ();
		}
		//////

	   /////Блоги
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 7 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Блоги');
			$root->makeRoot ();
			$root->setScopeIdValue ( 7 ); 
			$root->save ();
		}
		//////

		
	   /////Разное
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 8 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Статьи');
			$root->makeRoot ();
			$root->setScopeIdValue ( 8 ); 
			$root->save ();
		}
		//////		

		
	   /////FAQ
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 9 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('FAQ');
			$root->makeRoot ();
			$root->setScopeIdValue ( 9 ); 
			$root->save ();
		}
		//////		

	    /////Дипломы
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 10 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Дипломы');
			$root->makeRoot ();
			$root->setScopeIdValue ( 10 ); 
			$root->save ();
		}
		//////	

	    /////Типы товаров
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 11 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Типы товаров');
			$root->makeRoot ();
			$root->setScopeIdValue ( 11 ); 
			$root->save ();
		}
		//////		

	   /////Журнал
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 12 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Журнал');
			$root->makeRoot ();
			$root->setScopeIdValue ( 12 ); 
			$root->save ();
		}
		//////
		
	   /////Журнал
		$c = new Criteria ( );
		$c->add ( FolderPeer::SCOPE, 13 );
		$d = FolderPeer::doCount ( $c );
		if ($d == 0) {
			$root = new Folder();
            $root->setName('Афиша');
			$root->makeRoot ();
			$root->setScopeIdValue ( 13 ); 
			$root->save ();
		}
		//////
				
		//die;
		
		*/
	   parent::executeIndex ($request);
	
	}
	
	/*
	 * Функция вывода формы добавления каталога
	 */
	public function executeAdd_folder_form() {
		
		if($this->getRequestParameter('near')=='true')
		{
			$this->near = 'true';
		}
		
		$f = FolderPeer::retrieveByPk ( $this->getRequestParameter ( 'id' ) );
		
		if (! $f)
			$this->forward ( 'errorpage', 'noparameter' );
		
		$this->form = new AddFolderForm ( );
		$this->root = $this->getRequestParameter ( 'id' );
	
	}
	
	/*
	 * Вызов формы редактирования материала аяксом
	 */
	public function executeShow_material_form(sfWebRequest $request) {
		
		////Проверяем на права
		if(!$this->getUser()->hasCredential('type_'.$this->getRequestParameter('type')))
		{
			$this->setTemplate('access');
			return sfView::SUCCESS;
		}
		////
		
		 if (is_null($this->filters))
	    {
	      $this->filters = $this->configuration->getFilterForm($this->getFilters());
	    }
		
		if($request->getParameter('mat_id'))
		{
		  $mat =MaterialPeer::retrieveByPK($request->getParameter('mat_id'));
		}
		else 
		{
		  $mat = new Material ( );	
		}
		
		///Устанавливаем каталог
		if($this->getRequestParameter('node'))
		{
			$m2f = new Mat2Folder();
			$m2f->setFolderId($this->getRequestParameter('node'));
			$mat->addMat2Folder($m2f);
		}
		////
	
	    /// Определяем связку mat2mat		
		if($this->getRequestParameter('from_id'))
		{

			$mat->setParentId( $this->getRequestParameter('from_id'));
			$rel = new Material2Material();
			$rel->setFromId($this->getRequestParameter('from_id'));
			$mat->addMaterial2MaterialRelatedByToId($rel);
		}
		
		    /// Определяем тип материала	
			if($this->getRequestParameter('type'))
			{
				$type  = $this->getRequestParameter('type');
			}
			else 
			{
				  $type  = 1;
			}	

			///Создаем фору по типу материала
		$mat->setTypeId($type);		
		$str = 'Type'.$type.'Form';
		$this->form = new $str($mat);
        $this->material = $this->form->getObject();	
		
        ///Выключаем аякс
        if($request->getParameter('no_ajax')=='true')
        {
        	$this->setTemplate('index');
        }
        else
        {
        	$this->setLayout(false);
        	sfConfig::set('sf_web_debug',false);
        }
	}
		
	
public function executeUpdate(sfWebRequest $request)
  {

  	
    $this->material = $this->getRoute()->getObject();  
    
      	
  	////Проверяем на права
		if(!$this->getUser()->hasCredential('type_'.$this->material->getTypeId()))
		{
			$this->setTemplate('access');
			return sfView::SUCCESS;
		}
   ////
    
    $str = 'Type'.$this->material->getTypeId().'Form';  
	$this->form = new $str($this->material);
    $this->processForm($request, $this->form);
    $this->setTemplate('index');
  }
  
public function executeCreate(sfWebRequest $request)
  {
       /////Засовываем фильтр
  		 if (is_null($this->filters))
	    {
	      $this->filters = $this->configuration->getFilterForm($this->getFilters());
	    }
      /////
      
    $str = 'Type'.$request->getParameter('material[type_id]').'Form'; 
    $this->form = new $str();
    $this->material = $this->form->getObject(); 
	
	
    $this->processForm($request, $this->form);
    $this->setTemplate('index');
  }
  
  
  public function executeEdit(sfWebRequest $request)
  {
  	
       /////Засовываем фильтр
  		 if (is_null($this->filters))
	    {
	      $this->filters = $this->configuration->getFilterForm($this->getFilters());
	    }
      /////
  	
  	$this->setTemplate('index');
  	//$this->material = $this->getRoute()->getObject();  
  	$this->material = MaterialPeer::retrieveByPK($request->getParameter('id'));  
    $str = 'Type'.$this->material->getTypeId().'Form';  
	$this->form = new $str($this->material);
        /// Определяем связку mat2mat			
		$c = new Criteria();
		$c->add(Material2MaterialPeer::TO_ID,  $this->material->getId());
		$c->add(MaterialPeer::TYPE_ID,1);
		$c->addJoin(Material2MaterialPeer::FROM_ID,MaterialPeer::ID);
		$p = MaterialPeer::doSelectOne($c);	
		 if($p)
		  {
		  	$this->mat_id = $p->getId();
		  } 
	/////Удаляем картинку	
    if($request->getParameter('del_img') and $request->getParameter('folder'))
    { 
    	//echo sfConfig::get('sf_upload_dir').'/material/_thumbnails/'.$this->material->getPhotoPath();
    	@unlink(sfConfig::get('sf_upload_dir').'/material/'.$request->getParameter('folder').'/'.$this->material->getPhotoPath());
    	@unlink(sfConfig::get('sf_upload_dir').'/material/'.$request->getParameter('folder').'/thumbnail/'.$this->material->getPhotoPath());
    	@unlink(sfConfig::get('sf_upload_dir').'/material/'.$request->getParameter('folder').'/_thumbnail/'.$this->material->getPhotoPath());
    }
   ///
   
    /////Удаляем картинкугалереи	
    if($request->getParameter('del_to_mat') and $request->getParameter('id')  and $request->getParameter('id_mat'))
    { 
    	//echo sfConfig::get('sf_upload_dir').'/material/_thumbnails/'.$this->material->getPhotoPath();
    	$m2m = Material2MaterialPeer::retrieveByPK($request->getParameter('id'), $request->getParameter('id_mat') );
    	$m2m->delete();
    	$m = MaterialPeer::retrieveByPK($request->getParameter('id_mat'));
    	
    	
    	unlink(sfConfig::get('sf_upload_dir').'/material/'.$m->getTypeMaterial()->getImageFolder().'/'.$m->getPhotoPath());
    	unlink(sfConfig::get('sf_upload_dir').'/material/'.$m->getTypeMaterial()->getImageFolder().'/thumbnail/'.$m->getPhotoPath());
    	unlink(sfConfig::get('sf_upload_dir').'/material/'.$m->getTypeMaterial()->getImageFolder().'/_thumbnail/'.$m->getPhotoPath());
    }
   ///
   
  }
  
  
  public function executeFilter(sfWebRequest $request)
  {
    $this->setPage(1);

    if ($request->hasParameter('_reset'))
    {
      $this->setFilters($this->configuration->getFilterDefaults());
      $this->getUser()->setAttribute('material.filters_folder', '');
      $this->redirect('@material');
    }

    $this->filters = $this->configuration->getFilterForm($this->getFilters());
  
    $this->filters->bind($request->getParameter($this->filters->getName()));
     
    if ($this->filters->isValid())
    {
      $this->setFilters($this->filters->getValues());

      $this->redirect('@material');
    }

    $this->pager = $this->getPager();
    $this->sort = $this->getSort();

    $this->setTemplate('index');
  }
  
  
protected function buildCriteria()
  {
    if (is_null($this->filters))
    {
      $this->filters = $this->configuration->getFilterForm($this->getFilters());
    }
  
    
    $criteria = $this->filters->buildCriteria($this->getFilters());
   
    ////Мой код 
    $ff = $this->getUser()->getAttribute('material.filters_folder');
    if(isset($ff) and $ff!='')
    {
    	
    	$criteria ->addJoin(Mat2FolderPeer::MATERIAL_ID,MaterialPeer::ID);
    	$criteria->addGroupByColumn(Mat2FolderPeer::MATERIAL_ID);
    	 foreach ($ff as $f)
    	 {
    	   $criteria ->addOr(Mat2FolderPeer::FOLDER_ID,$f);
    	 }
    }

    $criteria->add(MaterialPeer::TYPE_ID,11);

    ///////
    
    $this->addSortCriteria($criteria);

    $event = $this->dispatcher->filter(new sfEvent($this, 'admin.build_criteria'), $criteria);
    $criteria = $event->getReturnValue();

    return $criteria;
  }

  
 protected function setFilters(array $filters)
  {
  	
  	///Мой код
  	$cur_fil = array();
  	//$cur_fil = $this->getUser()->getAttribute('material.filters_folder');
  	if ($this->getRequestParameter('filter_folder') and @!in_array($this->getRequestParameter('filter_folder'),$cur_fil) )
  	{
  		$cur_fil[] =  $this->getRequestParameter('filter_folder');
  		$this->getUser()->setAttribute('material.filters_folder', $cur_fil);		
  	}
    /////
    return $this->getUser()->setAttribute('material.filters', $filters, 'admin_module');
  }
  

  public function executeDel_image(sfWebRequest $request) {
  	
  	$this->forward('material','edit');
  	
  }
  
}
